package cn.baddonkey.superqueryjavasdk.interfaces.impl;

import cn.baddonkey.superqueryjavasdk.entity.request.QueryParam;
import cn.baddonkey.superqueryjavasdk.entity.vo.ModuleQueryConfigVo;
import cn.baddonkey.superqueryjavasdk.entity.vo.ModuleQuerySelectFieldVo;
import cn.baddonkey.superqueryjavasdk.interfaces.ModuleConfigAssembleInterface;
import org.springframework.lang.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ModuleConfigAssemble implements ModuleConfigAssembleInterface {
    private final static Pattern replacementPattern = Pattern.compile("\\$\\{(.*?)}");

    @Override
    public String generateSql(ModuleQueryConfigVo moduleQueryConfigVo, List<QueryParam> params) {
        List<ModuleQuerySelectFieldVo> selectFieldVoList = moduleQueryConfigVo.getSelectFieldVoList();
        if (selectFieldVoList == null) {
            selectFieldVoList = new ArrayList<>();
        }

        if (!selectFieldVoList.isEmpty()) {
            selectFieldVoList = this.filterValid(selectFieldVoList);
        }
        // TODO 拼装逻辑
        return null;
    }

    public @Nullable Map<String, ModuleQuerySelectFieldVo> selectFieldVoMap(List<ModuleQuerySelectFieldVo> voList) {
        return voList.stream().collect(Collectors.toMap(o -> String.valueOf(o.getId()), Function.identity()));
    }

    /**
     * 找出 select field 的 isValid == 1 and isDeleted == 0 的值
     *
     * @param voList 配置中的 select 值
     * @return 筛选结果
     */
    public List<ModuleQuerySelectFieldVo> filterValid(List<ModuleQuerySelectFieldVo> voList) {
        return voList.stream()
                .filter(o -> {
                    Integer isValid = o.getIsValid();
                    return isValid != null && isValid == 1;
                })
                .filter(o -> {
                    Integer isDeleted = o.getIsDeleted();
                    return isDeleted != null && isDeleted == 0;
                })
                .collect(Collectors.toList());
    }
}
